package com.sbio.udiapp.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.GridLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sbio.udiapp.BtActivity;
import com.sbio.udiapp.BuildConfig;
import com.sbio.udiapp.R;
import com.sbio.udiapp.common.bean.PrintVo;
import com.sbio.udiapp.cpcl.PrintUtil;
import com.sbio.udiapp.databinding.ActivityMainBinding;
import com.sbio.udiapp.di.ActivityManager;
import com.sbio.udiapp.net.api.ApiService;
import com.sbio.udiapp.net.bean.AjaxResult;
import com.sbio.udiapp.net.exception.ApiException;
import com.sbio.udiapp.net.exception.ErrorConsumerAdapter;
import com.sbio.udiapp.net.response.ResponseTransformer;
import com.sbio.udiapp.ui.model.RawMaterialListItemView;
import com.sbio.udiapp.util.ApiServiceUtil;
import com.sbio.udiapp.util.DefaultSharedPreferencesUtil;
import com.sbio.udiapp.util.DialogUtil;
import com.sbio.udiapp.util.DownLoadManager;
import com.sbio.udiapp.util.JsonUtil;
import com.sbio.udiapp.util.SharedPreferencesUtil;
import com.sbio.udiapp.util.SoundPlayerUtil;
import com.sbio.udiapp.util.ToastUtil;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

import javax.inject.Inject;

import cpcl.PrinterHelper;
import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@AndroidEntryPoint
public class MainActivity extends BaseBroadCastActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity_TAG";
    private ActivityMainBinding binding;

    Handler handler = new Handler();

    @Inject
    ApiService apiService;

    String localVersion;

    String updateApkUrl = "https://labour.s-sbio.com/profile/upload/apk/udi.apk"; // 初始化Logback

    java.util.function.Consumer<String> currentDialogConsumer;

    AlertDialog currentAlertDialog = null;

    String scanFunction = null;

    boolean rawMaterialCodesForSubPackaging_open = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Activity全屏显示，隐藏状态栏和导航栏
        /*getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
        );*/


        binding.btnPacking.setOnClickListener(this);
        binding.btnUnpacking.setOnClickListener(this);
//        binding.btnOutStock.setOnClickListener(this);
//        binding.btnUnOutStock.setOnClickListener(this);
        binding.btnBt.setOnClickListener(this);
        binding.btnPrint.setOnClickListener(this);
        binding.btnReprint.setOnClickListener(this);
        binding.btnBoxPrint.setOnClickListener(this);
        binding.btnBoxPrintCurrent.setOnClickListener(this);
        binding.btnRepairBox.setOnClickListener(this);
        binding.btnTest.setOnClickListener(this);
        binding.btnOutStockApply.setOnClickListener(this);
        binding.btnInWhichPack.setOnClickListener(this);
        binding.btnPushMo.setOnClickListener(this);
        binding.btnPrintExpress.setOnClickListener(this);
        binding.btnInvalidWaybill.setOnClickListener(this);
        binding.btnAntiInvalidWaybill.setOnClickListener(this);
        binding.btnUdiDataDownload.setOnClickListener(this);
        binding.btnComparePrice.setOnClickListener(this);
        binding.btnReceiveBill.setOnClickListener(this);
        binding.btnRawMaterialCodesForSubPackaging.setOnClickListener(this);
        binding.btnRawMaterialCodesForSubPackagingPro.setOnClickListener(this);
        SharedPreferencesUtil.init(this);
        boolean login = SharedPreferencesUtil.getBoolean("login", false);
        if (!login) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }
        //如果是生产部，隐藏出库申请单和在哪个箱子中
        settingButtonAuth();

        String selectedBDAddress = SharedPreferencesUtil.getString("selectedBDAddress");
        String SelectedBDName = SharedPreferencesUtil.getString("SelectedBDName");
        Log.i("tag112", "t" + selectedBDAddress);
        log112();
        connectBT(selectedBDAddress, SelectedBDName);

        //设置定时任务，定时上传文件
//        MyAlarmManager.setRepeatingAlarm(this);

//        apiService.hello("world");

//        handler.postDelayed(this::checkAndUpdateVersionSilence, 1000 * 15);

//        binding.btnPrint.setVisibility(View.INVISIBLE);


        /*binding.btnPrint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                PrintUtil.printQR("aaa");
                ToastUtil.show(R.string.toast_add_success);
            }
        });*/
    }

    /**
     * 设置按钮权限
     */
    private void settingButtonAuth() {
        GridLayout root = binding.getRoot();
        root.removeAllViews();
        List<View> showViews = new ArrayList<>();
        if (DefaultSharedPreferencesUtil.useDeptIsProduct(this)) {
            //生产部
            showViews.add(binding.btnPacking);
            showViews.add(binding.btnUnpacking);
            showViews.add(binding.btnReprint);
            showViews.add(binding.btnBoxPrint);
            showViews.add(binding.btnBoxPrintCurrent);
            showViews.add(binding.btnPushMo);
            showViews.add(binding.btnUdiDataDownload);
            showViews.add(binding.btnRepairBox);
        } else {
            //仓库
            showViews.add(binding.btnPacking);
            showViews.add(binding.btnUnpacking);
            showViews.add(binding.btnReprint);
            showViews.add(binding.btnBoxPrint);
            showViews.add(binding.btnBoxPrintCurrent);
            showViews.add(binding.btnOutStockApply);
            showViews.add(binding.btnInWhichPack);
            showViews.add(binding.btnPrintExpress);
            showViews.add(binding.btnInvalidWaybill);
            showViews.add(binding.btnComparePrice);
            showViews.add(binding.btnReceiveBill);
            showViews.add(binding.btnRawMaterialCodesForSubPackaging);
            showViews.add(binding.btnRawMaterialCodesForSubPackagingPro);
            showViews.add(binding.btnRepairBox);
        }
        //蓝牙和连接文字
        showViews.add(binding.btnBt);
        showViews.add(binding.activityMainBtInfo);
//        showViews.add(binding.btnPrint);
//
//        List<Integer> idList = showViews.stream().map(View::getId).collect(Collectors.toList());
//        for (int i = 0; i < binding.getRoot().getChildCount(); i++) {
//            View child = binding.getRoot().getChildAt(0);
//            child.setVisibility(View.GONE);
//            GridLayout.Spec rowSpec = GridLayout.spec(0); // 行
//            GridLayout.Spec colSpec = GridLayout.spec(0); // 跨越两列
//            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams(rowSpec, colSpec);
//            child.setLayoutParams(layoutParams);
//        }
//
//
        for (int i = 0; i < showViews.size(); i++) {
            View view = showViews.get(i);
            view.setVisibility(View.VISIBLE);
//            GridLayout.Spec rowSpec = GridLayout.spec(i / 2); // 行
//            GridLayout.Spec colSpec = GridLayout.spec(i % 2); // 跨越两列
//            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams(rowSpec, colSpec);
//
//            layoutParams.width = 300;
//            layoutParams.height = GridLayout.LayoutParams.WRAP_CONTENT;
//
//            view.setLayoutParams(layoutParams);


            // 计算当前视图所在的行和列
            int row = i / 2;
            int column = i % 2;

            // 创建布局参数，明确指定行和列
            GridLayout.Spec rowSpec = GridLayout.spec(row);
            GridLayout.Spec colSpec = GridLayout.spec(column);
            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams(rowSpec, colSpec);

            // 设置适当的宽高和间距
            layoutParams.width = 0; // 0表示按权重分配
            layoutParams.height = GridLayout.LayoutParams.WRAP_CONTENT;
            layoutParams.columnSpec = GridLayout.spec(column, 1f); // 列权重为1，平均分配宽度
            layoutParams.setMargins(16, 16, 16, 16); // 可选：添加边距

            view.setLayoutParams(layoutParams);




            binding.getRoot().addView(view);
        }


       /* //如果是生产部，隐藏出库申请单和在哪个箱子中
        if (DefaultSharedPreferencesUtil.useDeptIsProduct(this)) {
            binding.btnOutStockApply.setVisibility(View.GONE);
            binding.btnInWhichPack.setVisibility(View.GONE);
            binding.btnPushMo.setVisibility(View.VISIBLE);
            binding.btnPrintExpress.setVisibility(View.GONE);
        } else {
            binding.btnOutStockApply.setVisibility(View.VISIBLE);
            binding.btnInWhichPack.setVisibility(View.VISIBLE);
            binding.btnPushMo.setVisibility(View.GONE);
            binding.btnPrintExpress.setVisibility(View.VISIBLE);
        }*/
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onBroadcastReceiver(String barcodeData) {
        if (currentDialogConsumer != null) {
            currentDialogConsumer.accept(barcodeData);
            currentAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
            currentDialogConsumer = null;
            return;
        }
        if (barcodeData.startsWith("SS")) {
            //该功能为打印原材料码
            if (!rawMaterialCodesForSubPackaging_open) {
                AlertDialog alertDialog = rawMaterialCodesForSubPackagingClick();
                alertDialog.setOnShowListener(dialog -> {
                    rawMaterialCodesForSubPackaging_open = true;
                    EditText editText = currentAlertDialog.findViewById(R.id.et_input1);
                    editText.setText(barcodeData);
                });
                alertDialog.show();
            } else {
                EditText editText = currentAlertDialog.findViewById(R.id.et_input1);
                editText.setText(barcodeData);

            }
        }

        if (barcodeData.startsWith("SOUT")) {
            //生产领料单
            if (!rawMaterialCodesForSubPackaging_open) {
                AlertDialog alertDialog = rawMaterialCodesForSubPackagingClick();
                alertDialog.setOnShowListener(dialog -> {
                    rawMaterialCodesForSubPackaging_open = true;
                    EditText editText = currentAlertDialog.findViewById(R.id.et_input3);
                    editText.setText(barcodeData);
                });
                alertDialog.show();
            } else {
                EditText editText = currentAlertDialog.findViewById(R.id.et_input3);
                editText.setText(barcodeData);

            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        settingButtonAuth();
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        Intent intent = null;
        switch (item.getItemId()) {
            case R.id.action_settings:
                intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                break;
            case R.id.action_current_version:
                DialogUtil.showCommonAlertDialog("当前版本为" + AppUtils.getAppVersionName());
                break;
            case R.id.action_update_version:
//                intent = new Intent(this, SettingsActivity.class);
//                startActivity(intent);
                checkAndUpdateVersion();


                Log.i("ttt", "onOptionsItemSelected: " + AppUtils.getAppVersionCode());
                break;
            case R.id.action_env:
                if (BuildConfig.DEBUG) {
//                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
//                    Log.i("tag113", JsonUtil.toJsonString(preferences.getAll()));
//                    String useDept = preferences.getString(getString(R.string.use_dept), "1111");
                    ToastUtil.show("当前环境为：开发环境");
                } else {
                    ToastUtil.show("当前环境为：生产环境");
                }
                break;
            case R.id.action_log:
                intent = new Intent(this, LogActivity.class);
                startActivity(intent);
                break;
            case R.id.action_logout:
                SharedPreferencesUtil.saveBoolean("login", false);
                intent = new Intent(MainActivity.this, LoginActivity.class);
                //退出登录
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
        }
        return true;
    }

    private void checkAndUpdateVersion() {
        apiService.apkVersion()
                .compose(ResponseTransformer.obtain())
                .subscribe(ajaxResult -> {
                    if (ajaxResult.getCode() != 0) {
                        //弹出提示框
                        DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
                        return;
                    }
                    if (ajaxResult.getData(Integer.class) > AppUtils.getAppVersionCode()) {
                        ToastUtil.showLong("正在下载中，请稍后。。。");
                        updateApk();
                    } else {
                        ToastUtil.showLong("已经是最新版本！");
                    }


                }, new ErrorConsumerAdapter());
    }


    /**
     * 静默检查更新
     */
    /*private void checkAndUpdateVersionSilence() {
        apiService.apkVersion()
                .compose(ResponseTransformer.obtain())
                .subscribe(ajaxResult -> {
                    if (ajaxResult.getCode() != 0) {
                        //弹出提示框
                        DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
                        return;
                    }
                    if (ajaxResult.getData(Integer.class) > AppUtils.getAppVersionCode()) {
                        DialogUtil.showCommonConfirmDialog("是否立即下载更新", () -> {
                            ToastUtil.showLong("正在下载中，请稍后。。。");
                            updateApk();
                        });
                    } else {
                        ToastUtil.showLong("已经是最新版本！");
                    }


                }, ErrorComsumerSupplier.of(() -> DialogUtil.showCommonAlertDialog("网络异常")));
        handler.postDelayed(this::checkAndUpdateVersionSilence, 1000 * 15);
    }*/
    private void updateApk() {
        Uri uri = Uri.parse(updateApkUrl);
//                AppUtils.installApp(uri);
//                AppUtils.installApp(new Uri("http://s-sbio.com/profile/upload/apk/udi.apk"));
//                PathUtils.getCachePathExternalFirst();

        RxPermissions rxPermissions = new RxPermissions((FragmentActivity) this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Throwable {
                new Thread(() -> {
                    File fileFromServer = null;
                    try {
                        fileFromServer = DownLoadManager.getFileFromServer(updateApkUrl, null);
                    } catch (Exception e) {

                        e.printStackTrace();
                    }
                    AppUtils.installApp(fileFromServer);
                }).start();
            }
        });
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.btn_packing: {
                boolean prepared = PrintUtil.checkPrintPrepared();
                if (!prepared) {
                    return;
                }
                intent = new Intent(this, PackingActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.btn_unpacking: {
                boolean prepared = PrintUtil.checkPrintPrepared();
                if (!prepared) {
                    return;
                }
                intent = new Intent(this, UnpackingActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.btn_out_stock_apply: {
                intent = new Intent(this, OutStockApplyActivity.class);
                startActivity(intent);
                break;
            }
            /*case R.id.btn_out_stock: {
                intent = new Intent(this, OutStockActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.btn_un_out_stock: {
                intent = new Intent(this, UnOutStockActivity.class);
                startActivity(intent);
                break;
            }*/
            case R.id.btn_bt: {
                intent = new Intent(this, BtActivity.class);
                intent.putExtra("TAG", 0);
                startActivityForResult(intent, 0);
                break;
            }
            case R.id.btn_reprint: {
                String printVoStr = SharedPreferencesUtil.getString("printVo");
                Log.i(TAG, "btn_reprint: " + printVoStr);
                if (Objects.equals(printVoStr, "")) {
                    ToastUtil.show("没有上次打印内容");
                    return;
                }
                PrintVo printVo = JsonUtil.parse(printVoStr, PrintVo.class);
                PrintUtil.printQR(printVo);
                break;
            }
            case R.id.btn_boxPrint: {
                // 创建一个 AlertDialog.Builder 对象
                /*AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请输入内容");
                final EditText input = new EditText(this);
                builder.setView(input);
                input.requestFocus();
                builder.setPositiveButton("确定", (dialog, which) -> {
                    String text = input.getText().toString();
                    if (!StringUtils.isEmpty(text)) {
                        apiService.getMaterialInfoByUdi(text)
                                .compose(ResponseTransformer.obtain())
                                .subscribe(ajaxResult -> {
                                    Object data = ajaxResult.getData();
                                    ObjectMapper objectMapper = new ObjectMapper();
                                    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                                    PrintVo printVo = objectMapper.convertValue(data, PrintVo.class);
                                    PrintUtil.printQR(printVo);
                                }, new ErrorConsumerAdapter() {
                                    @Override
                                    public void error(ApiException ex) {
                                        super.error(ex);
                                        //处理异常
                                        ToastUtil.show(ex.getErrMsg());
                                    }
                                });
                    }
                    // 处理输入的内容
                });
                builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

                AlertDialog dialog = builder.create();
                input.setOnEditorActionListener((v1, actionId, event) -> {
                    if (!StringUtils.isEmpty(v1.getText())) {
                        dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
                    }
                    return false;
                });
                dialog.show();*/
                currentDialogConsumer = text -> {
                    if (!StringUtils.isEmpty(text)) {
                        apiService.getMaterialInfoByUdi(text)
                                .compose(ResponseTransformer.obtain())
                                .subscribe(ajaxResult -> {
                                    Object data = ajaxResult.getData();
                                    ObjectMapper objectMapper = new ObjectMapper();
                                    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                                    PrintVo printVo = objectMapper.convertValue(data, PrintVo.class);
                                    PrintUtil.printQR(printVo);
                                }, new ErrorConsumerAdapter() {
                                    @Override
                                    public void error(ApiException ex) {
                                        super.error(ex);
                                        //处理异常
                                        ToastUtil.show(ex.getErrMsg());
                                    }
                                });
                    }
                };
                currentAlertDialog = DialogUtil.showConfirmDialogEditText("请输入内容", currentDialogConsumer);
                break;
            }
            case R.id.btn_boxPrintCurrent: {
                // 创建一个 AlertDialog.Builder 对象
                currentDialogConsumer = text -> apiService.getMaterialInfoByPackNo(text)
                        .compose(ResponseTransformer.obtain())
                        .subscribe(ajaxResult -> {
                            Object data = ajaxResult.getData();
                            ObjectMapper objectMapper = new ObjectMapper();
                            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                            PrintVo printVo = objectMapper.convertValue(data, PrintVo.class);
                            PrintUtil.printQR(printVo);
                        }, new ErrorConsumerAdapter());
                currentAlertDialog = DialogUtil.showConfirmDialogEditText("请输入内容", currentDialogConsumer);
                /*AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请输入内容");
                final EditText input = new EditText(this);
                builder.setView(input);
                input.requestFocus();
                builder.setPositiveButton("确定", (dialog, which) -> {
                    String text = input.getText().toString();
                    if (!StringUtils.isEmpty(text)) {
                        apiService.getMaterialInfoByPackNo(text)
                                .compose(ResponseTransformer.obtain())
                                .subscribe(ajaxResult -> {
                                    Object data = ajaxResult.getData();
                                    ObjectMapper objectMapper = new ObjectMapper();
                                    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                                    PrintVo printVo = objectMapper.convertValue(data, PrintVo.class);
                                    PrintUtil.printQR(printVo);
                                }, new ErrorConsumerAdapter());
                    }
                    // 处理输入的内容
                });
                builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

                AlertDialog dialog = builder.create();
                input.setOnEditorActionListener((v1, actionId, event) -> {
                    if (!StringUtils.isEmpty(v1.getText())) {
                        dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
                    }
                    return false;
                });
                dialog.show();*/
                break;
            }

            case R.id.btn_repairBox: {

                // 创建一个 AlertDialog.Builder 对象
                currentDialogConsumer = text -> {
                    if (text.startsWith("M")) {
                        text = "X" + text;
                    }
                    apiService.getMaterialInfoByPackNo(text)
                            .compose(ResponseTransformer.obtain())
                            .subscribe(ajaxResult -> {
                                Object data = ajaxResult.getData();
                                ObjectMapper objectMapper = new ObjectMapper();
                                objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                                PrintVo printVo = objectMapper.convertValue(data, PrintVo.class);
                                PrintUtil.printQR(printVo);
                            }, new ErrorConsumerAdapter());
                };
                currentAlertDialog = DialogUtil.showConfirmDialogEditText("请输入内容", currentDialogConsumer);
                break;
            }
            case R.id.btn_inWhichPack: {
                // 创建一个 AlertDialog.Builder 对象
                /*AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请输入内容");
                final EditText input = new EditText(this);
                builder.setView(input);
                input.requestFocus();
                builder.setPositiveButton("确定", (dialog, which) -> {
                    String text = input.getText().toString();
                    if (!StringUtils.isEmpty(text)) {
                        apiService.getAllAncestralPackNoByNo(text)
                                .compose(ResponseTransformer.obtain())
                                .subscribe(ajaxResult -> {
                                    String data = ajaxResult.getData(String.class);
                                    DialogUtil.showCommonAlertDialog(data);
                                }, new ErrorConsumerAdapter() {
                                    @Override
                                    public void error(ApiException ex) {
                                        super.error(ex);
                                        //处理异常
                                        ToastUtil.show(ex.getErrMsg());
                                    }
                                });
                    }
                    // 处理输入的内容
                });
                builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

                AlertDialog dialog = builder.create();
                input.setOnEditorActionListener((v1, actionId, event) -> {
                    if (!StringUtils.isEmpty(v1.getText())) {
                        dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
                    }
                    return false;
                });
                dialog.show();
                currentDialogConsumer = text->apiService.getAllAncestralPackNoByNo(text)
                        .compose(ResponseTransformer.obtain())
                        .subscribe(ajaxResult -> {
                            String data = ajaxResult.getData(String.class);
                            DialogUtil.showCommonAlertDialog(data);
                        }, new ErrorConsumerAdapter() {
                            @Override
                            public void error(ApiException ex) {
                                super.error(ex);
                                //处理异常
                                ToastUtil.show(ex.getErrMsg());
                            }
                        });*/
                currentDialogConsumer = text -> apiService.getAllAncestralPackNoByNo(text)
                        .compose(ResponseTransformer.obtain())
                        .subscribe(ajaxResult -> {
                            String data = ajaxResult.getData(String.class);
                            DialogUtil.showCommonAlertDialog(data);
                        }, new ErrorConsumerAdapter() {
                            @Override
                            public void error(ApiException ex) {
                                super.error(ex);
                                //处理异常
                                ToastUtil.show(ex.getErrMsg());
                            }
                        });
                currentAlertDialog = DialogUtil.showConfirmDialogEditText("请输入内容", currentDialogConsumer);
                break;
            }
            case R.id.btn_pushMo: {

                // 创建一个 AlertDialog.Builder 对象
                /*AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请输入箱码或盒码");
                final EditText input = new EditText(this);
                builder.setView(input);
                input.requestFocus();
                builder.setPositiveButton("确定", (dialog, which) -> {
                    String text = input.getText().toString();
                    if (!StringUtils.isEmpty(text)) {
                        apiService.pushMo(text)
                                .compose(ResponseTransformer.obtain())
                                .subscribe(ajaxResult -> {
                                    String data = ajaxResult.getData(String.class);
                                    ToastUtil.show(data);
                                    SoundPlayerUtil.playSuccess();
                                }, new ErrorConsumerAdapter() {
                                    @Override
                                    public void error(ApiException ex) {
                                        super.error(ex);
                                        //处理异常
                                        ToastUtil.show(ex.getErrMsg());
                                        SoundPlayerUtil.playFail();
                                    }
                                });
                    }
                    // 处理输入的内容
                });
                builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

                AlertDialog dialog = builder.create();
                input.setOnEditorActionListener((v1, actionId, event) -> {
                    if (!StringUtils.isEmpty(v1.getText())) {
                        dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
                    }
                    return false;
                });
                dialog.show();*/
                currentDialogConsumer = text -> apiService.pushMo(text)
                        .compose(ResponseTransformer.obtain())
                        .subscribe(ajaxResult -> {
                            String data = ajaxResult.getData(String.class);
                            ToastUtil.show(data);
                            SoundPlayerUtil.playSuccess();
                        }, new ErrorConsumerAdapter() {
                            @Override
                            public void error(ApiException ex) {
                                super.error(ex);
                                //处理异常
                                ToastUtil.show(ex.getErrMsg());
                                SoundPlayerUtil.playFail();
                            }
                        });
                DialogUtil.showConfirmDialogEditText("请输入箱码或盒码", currentDialogConsumer);
                break;
            }
            case R.id.btn_printExpress: {
                intent = new Intent(this, ExpressActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.btn_receive_bill: {
                intent = new Intent(this, RawMaterialActivity.class);
                startActivity(intent);
                break;
            }

            case R.id.btn_invalid_waybill: {
                // 创建一个 AlertDialog.Builder 对象
                /*AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请输入内容");
                final EditText input = new EditText(this);
                builder.setView(input);
                input.requestFocus();
                builder.setPositiveButton("确定", (dialog, which) -> {
                    String text = input.getText().toString();
                    if (!StringUtils.isEmpty(text)) {
                        ApiServiceUtil.enqueue(() -> apiService.deleteInvalidWaybill(text), new Callback<AjaxResult>() {
                            @Override
                            public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                                AjaxResult ajaxResult = response.body();
                                if (ajaxResult.isSuccess()) {

                                    ToastUtil.showSuccess("作废成功");
                                } else {
                                    DialogUtil.showErrorAlertDialog("作废失败" + ajaxResult.getMsg());
                                }
                            }

                            @Override
                            public void onFailure(Call<AjaxResult> call, Throwable t) {
                                DialogUtil.showErrorAlertDialog(t.getMessage());
                            }
                        });

                    }
                    // 处理输入的内容
                });
                builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

                AlertDialog dialog = builder.create();
                input.setOnEditorActionListener((v1, actionId, event) -> {
                    if (!StringUtils.isEmpty(v1.getText())) {
                        dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
                    }
                    return false;
                });
                dialog.show();*/
                currentDialogConsumer = text -> ApiServiceUtil.enqueue(() -> apiService.deleteInvalidWaybill(text), new Callback<AjaxResult>() {
                    @Override
                    public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                        AjaxResult ajaxResult = response.body();
                        if (ajaxResult.isSuccess()) {

                            ToastUtil.showSuccess("作废成功");
                        } else {
                            DialogUtil.showErrorAlertDialog("作废失败" + ajaxResult.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(Call<AjaxResult> call, Throwable t) {
                        DialogUtil.showErrorAlertDialog(t.getMessage());
                    }
                });
                currentAlertDialog = DialogUtil.showConfirmDialogEditText("请输入内容", currentDialogConsumer);

                break;
            }

            case R.id.btn_anti_invalid_waybill: {
                // 创建一个 AlertDialog.Builder 对象
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请输入内容");
                final EditText input = new EditText(this);
                builder.setView(input);
                input.requestFocus();
                builder.setPositiveButton("确定", (dialog, which) -> {
                    String text = input.getText().toString();
                    if (!StringUtils.isEmpty(text)) {
                        ApiServiceUtil.enqueue(() -> apiService.antiInvalidWaybill(text), new Callback<AjaxResult>() {
                            @Override
                            public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                                AjaxResult ajaxResult = response.body();
                                if (ajaxResult.isSuccess()) {
                                    ToastUtil.showSuccess("反作废成功");
                                } else {
                                    DialogUtil.showCommonAlertDialog("反作废失败" + ajaxResult.getMsg());
                                }
                            }

                            @Override
                            public void onFailure(Call<AjaxResult> call, Throwable t) {
                                DialogUtil.showCommonAlertDialog(t.getMessage());
                            }
                        });
                    }
                    // 处理输入的内容
                });
                builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

                AlertDialog dialog = builder.create();
                input.setOnEditorActionListener((v1, actionId, event) -> {
                    if (!StringUtils.isEmpty(v1.getText())) {
                        dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
                    }
                    return false;
                });
                dialog.show();
                break;
            }
            case R.id.btn_udi_data_download: {
                intent = new Intent(this, UdiDataDownloadActivity.class);
                startActivity(intent);
                break;
            }

            case R.id.btn_compare_price: {
                intent = new Intent(this, ComparePriceActivity.class);
                startActivity(intent);
                break;
            }

            case R.id.btn_print: {
                // 注册偏好设置更改监听器

                /*SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
                ObjectMapper objectMapper = new ObjectMapper();
                String s = null;
                try {
                    s = objectMapper.writeValueAsString(sharedPreferences.getString(getString(R.string.use_dept),""));
                    Log.i("xxxxx", s);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                ToastUtil.showLong(this.getPackageName());*/
                log112();
//                apiService.printTest();
                PrintVo printVo = new PrintVo();
                printVo.setLot("230704001");
                printVo.setSpec("48 Tests/Kit（8 tests/platex 6）");
                printVo.setMaterialName("Streptococcus pneumoniae,Legionella pneumophila and Haemophilus influenzae Real Time PCR Kit");
                printVo.setMaterialNo("C.02.01.008.0289（RUO）");
                printVo.setCount(111);
                printVo.setPackNo("XM230704001");
                printVo.setRegistrationCertificateNo("registrationCertificateNo");
                printVo.setArticleNo("1234561231456");
                PrintUtil.printQR(printVo);
                SharedPreferencesUtil.saveString("printVo", JsonUtil.toJsonString(printVo));
                ToastUtil.show(Build.VERSION.SDK_INT + "");
                break;
            }
            case R.id.btn_rawMaterialCodesForSubPackaging: {
                AlertDialog alertDialog = rawMaterialCodesForSubPackagingClick();
                alertDialog.show();
                break;
            }
            case R.id.btn_rawMaterialCodesForSubPackagingPro: {
                intent = new Intent(this,RawMaterialSubPackActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.btn_test: {
                String url = "https://labour.s-sbio.com/common/download/resource?resource=/profile/upload/1.png";
//                url = "https://labour.s-sbio.com/hik/hello";
                url = "https://labour.s-sbio.com/profile/upload/1.png";
                System.out.println(url);

                apiService.getImage(url).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
                        try {
                            PrinterHelper.printAreaSize("0", "600", "1040", "1040", "1");
                            PrinterHelper.printBitmapCPCL(bitmap, 0, 0, 0, 0, 0);
                            PrinterHelper.Form();
                            PrinterHelper.Print();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
//                        Bitmap bitmap = glide.with(MainActivity.this)
//                                .asBitmap()
//                                .load(response.body().bytes())
//                                .submit()
//                                .get();
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        DialogUtil.showCommonAlertDialog(t.getMessage());
                    }
                });
                ToastUtil.show("success" + new Random().nextInt(66));

                /*binding.btnTest.setText("打印1次");

                try {
                    for (int i = 0; i < 1; i++) {
                        printWhite();
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                break;*/




                /*String requestUniParam = RequestUniParam.create("调用hello方法").toJson();
                ApiServiceUtil.enqueue(() -> apiService.hello("张三", requestUniParam), new Callback<AjaxResult>() {
                    @Override
                    public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                        AjaxResult ajaxResult = response.body();
                        if (ajaxResult.isSuccess()) {
                            ToastUtil.show("调用成功");
                        } else {
                            DialogUtil.showCommonAlertDialog("调用失败" + ajaxResult.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(Call<AjaxResult> call, Throwable t) {
                        DialogUtil.showCommonAlertDialog(t.getMessage());
                    }
                });*/

                /*PrintVo printVo = new PrintVo();
                printVo.setLot("230704001");
                printVo.setSpec("48 Tests/Kit（8 tests/platex 6）");
                printVo.setMaterialName("Streptococcus pneumoniae,Legionella pneumophila and Haemophilus influenzae Real Time PCR Kit");
                printVo.setMaterialNo("C.02.01.008.0289（RUO）");
                printVo.setCount(111);
                printVo.setPackNo("XM230704001");
                printVo.setRegistrationCertificateNo("registrationCertificateNo");
                printVo.setArticleNo("1234561231456");
                PrintUtil.printQR(printVo);
                SharedPreferencesUtil.saveString("printVo", JsonUtil.toJsonString(printVo));*/
                /*binding.btnTest.setText("打印10次");
                try {
                    for (int i = 0; i < 10; i++) {
                        PrinterHelper.printAreaSize("0", "600", "400", "400", "1");
//                    PrinterHelper.Text(PrinterHelper.TEXT, "2", "0", "0", "0", "ABNCDEFG ");
                        PrinterHelper.Form();
                        PrinterHelper.Print();
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }*/

                /*String content = String.format("点击了“%s”按钮", getString(R.string.test));
                String requestUniParam = RequestUniParam.create(content).toJson();
                Call<AjaxResult> call = apiService.logTest("123", requestUniParam);
                call.enqueue(new Callback<AjaxResult>() {
                    @Override
                    public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {

                    }

                    @Override
                    public void onFailure(Call<AjaxResult> call, Throwable t) {
                        ToastUtil.showError(t.getMessage());
                    }
                });*/
                break;
            }


        }
    }

    private AlertDialog rawMaterialCodesForSubPackagingClick() {
        Context context = ActivityManager.getCurrentActivity();

        // 加载自定义布局
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_custom_input, null);
        EditText etInput1 = view.findViewById(R.id.et_input1);
        etInput1.setHint("请扫码输入分装的二维码");
        etInput1.setText("");
//        etInput1.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
        EditText etInput2 = view.findViewById(R.id.et_input2);
        etInput2.setHint("请输入箱数");
        etInput2.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
        etInput2.setText("0");
        EditText etInput3 = view.findViewById(R.id.et_input3);
        etInput3.setVisibility(View.VISIBLE);
        etInput3.setHint("扫码输入领料单单号");
//        etInput3.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
        etInput3.setText("");

        // 构建 AlertDialog
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        currentAlertDialog = builder.setTitle("确认打印原材料二维码?")
                .setView(view)
                .setPositiveButton("确定", (dialog, which) -> {
                    String input1 = etInput1.getText().toString();
                    Long input2 = null;
                    try {
                        input2 = Long.valueOf(etInput2.getText().toString());
                    } catch (NumberFormatException e) {
                        input2 = 0L;
                    }

                    Long finalInput2 = input2;
                    ApiServiceUtil.enqueue(() -> apiService.selectRawMaterial(input1,etInput3.getText().toString()), new Callback<AjaxResult>() {
                        @Override
                        public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                            hideProcess();
                            AjaxResult ajaxResult = response.body();
                            if (Objects.requireNonNull(ajaxResult).isSuccess()) {

                                List<RawMaterialListItemView> views = ajaxResult.getDataListByClz(RawMaterialListItemView.class);
                                views.forEach(it -> it.setQty(finalInput2));
                                views.forEach(it -> {
                                    PrintUtil.printRawMaterial(it);
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                });
//                                    views.forEach(PrintUtil::printRawMaterial);
                                ToastUtil.showSuccess("打印成功");
                                //            PrintUtil.printQR4Product(new PrintVo());
                            } else {
                                SoundPlayerUtil.playFail();
                                DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
                            }
                        }

                        @Override
                        public void onFailure(Call<AjaxResult> call, Throwable t) {
                            hideProcess();
                            DialogUtil.showErrorAlertDialog(t.getMessage());
                        }
                    });


                    rawMaterialCodesForSubPackaging_open = false;
                })
                .setNegativeButton("取消", null)
                .setOnDismissListener(dialog -> rawMaterialCodesForSubPackaging_open = false)
                .setCancelable(true)
                .create();
        currentAlertDialog.setOnShowListener(dialog -> rawMaterialCodesForSubPackaging_open = true);
        return currentAlertDialog;
    }

    private static void printWhite() throws Exception {
        PrinterHelper.printAreaSize("0", "600", "400", "400", "1");
//                    PrinterHelper.Text(PrinterHelper.TEXT, "2", "0", "0", "0", "ABNCDEFG ");
        double barcodeY = 10;
        double textHeight = 10;
        String textFont = "2";
        double textX = 10;
        barcodeY += textHeight * 3;
        String number = "";
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);
        barcodeY += textHeight * 3;
        PrinterHelper.Text(PrinterHelper.TEXT, textFont, "0", textX + "", barcodeY + "", number);

        PrinterHelper.Form();
        PrinterHelper.Print();
    }


    //call back by scan bluetooth printer
    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        try {
            String strIsConnected;
            if (data == null)
                return;
            switch (resultCode) {
                case RESULT_CANCELED:
                    connectBT(data.getStringExtra("SelectedBDAddress"), data.getStringExtra("SelectedBDName"));
                    break;
                case PrinterHelper.ACTIVITY_CONNECT_WIFI:
                    String resultWIFI = data.getExtras().getString("is_connected");
//                    if(resultWIFI.equals("OK"))
//                        txtTips.setText(thisCon.getString(R.string.activity_main_connected));
                    return;
                case RESULT_OK:
//	  				if (requestCode==ImageSelector.IMAGE_REQUEST_CODE)
//						setPrintDialog(data);
//					return;
//                    if (requestCode==PictureConfig.CHOOSE_REQUEST)
//                        setPrintDialog(data);
                    return;
                case PrinterHelper.ACTIVITY_PRNFILE:
                    String strPRNFile = data.getExtras().getString("FilePath");
                    PrinterHelper.PrintBinaryFile(strPRNFile);
                    return;
            }
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onActivityResult ")).append(e.getMessage()).toString());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void connectBT(final String selectedBDAddress, String selectedBDName) {
        if (TextUtils.isEmpty(selectedBDAddress))
            return;
        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage(getString(R.string.activity_devicelist_connect));
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    final int result = PrinterHelper.portOpenBT(getApplicationContext(), selectedBDAddress);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            binding.activityMainBtInfo.setText(result);
                            if (result == 0) {
                                SharedPreferencesUtil.saveString("selectedBDAddress", selectedBDAddress);
                                SharedPreferencesUtil.saveString("selectedBDName", selectedBDName);
                                log112();
                                binding.activityMainBtInfo.setText(String.format("%s%s", MainActivity.this.getString(R.string.activity_main_connected), selectedBDName));
                            } else
                                binding.activityMainBtInfo.setText(MainActivity.this.getString(R.string.activity_main_connecterr) + result);
                        }
                    });
                    progressDialog.dismiss();
                } catch (Exception e) {
                    progressDialog.dismiss();
                }
            }
        }.start();
    }


    private String getVersionName() throws Exception {
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageManager packageManager = getPackageManager();
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
                0);
        return packInfo.versionName;
    }

    public void log112() {
        Map<String, ?> all = SharedPreferencesUtil.getAll();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Log.i("tag112", objectMapper.writeValueAsString(all));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /*public void a() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, VersionCheckReceiver.class);
        int flag = 0;
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, flag);

// 设置定时任务，这里设置为每天检查一次
        long interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
        interval = 1 * 60 * 1000;
        long triggerTime = System.currentTimeMillis() + interval;
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, triggerTime, interval, pendingIntent);
    }*/
}